package ldkxingzhe.l365calendar.utils;

import android.content.Context;
import android.os.PowerManager;

import ldkxingzhe.l365calendar.App;

/**
 * 全局的一个轻型的唤醒锁。
 */
public class LightWakeLock {
    private static final String TAG = "LightWakeLock";
    private static PowerManager.WakeLock mWakeLock;

    private static volatile int wakeCount = 0;

    private static void makeSureWakeLockExist(Context context){
        if(mWakeLock == null){
            synchronized (TAG){
                if(mWakeLock == null){
                    PowerManager powerManager
                            = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
                    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
                    mWakeLock.setReferenceCounted(true);
                    LogUtil.v(TAG, "new WakeLock");
                }
            }
        }
    }

    public static void acquire(){
        makeSureWakeLockExist(App.applicationContext);
        mWakeLock.acquire();
        wakeCount++;
        LogUtil.v(TAG, "acquire, and wakeCount is " + wakeCount);
    }

    public static void release(){
        if(mWakeLock == null){
            synchronized (TAG){
                if(mWakeLock == null){
                    wakeCount = 0;
                    return;
                }
            }
        }

        mWakeLock.release();
        wakeCount--;
        if(wakeCount <= 0) mWakeLock = null;
        LogUtil.v(TAG, "release, and wakeCount is " + wakeCount);
    }
}
